
import Dialog from '@vant/weapp/dialog/dialog';

var api = require('../../../utils/api.js')
var $ = require('../../../utils/util.js')
var regeneratorRuntime = require('../../../utils/runtime.js')
var app = getApp()

Page({
  data: {
    info: null, // 详情数据
    tabList: [
      { name: '执行计划', type: 1 }, 
      { name: '现场检修', type: 2 }, 
      // { name: '材料消耗', type: 3 }, 
      // { name: '工作报告', type: 4 }
    ], // tab
    list: ['', '', '',],
    currentTab: 0,
    activeNames: ['1'],
    result: '', // 结果
    check_id:0, // 检修id
    status:'', // 检修状态(不动为了判断开关是否开)
    status_f:'', // 为了判断
    image1:'',
    image2:'',
    image3:'',
    isLose: false,//作废弹窗
    invalidReason: '', // 作废理由

    _longitude: 116.3972282409668, //当前地图位置的中心点(默认定位北京)
    _latitude: 39.90960456049752, //当前地图位置的中心点(默认定位北京)
    _scale: 13, //当前地图的缩放系数
    markers:[//地图图标
      {
      id: 0
      ,iconPath: "/assets/map_localtion_red.png"
      ,longitude: 116.3972282409668
      ,latitude: 39.90960456049752
      ,width: 30
      ,height: 30
      }
    ]
  },
  onLoad: function (options) {
    if ('check_id' in options){
      this.setData({
        check_id: options.check_id,
        station_id: options.station_id,
        ticket_num: options.ticket_num ,
      })
    }

    this._info(); // 检修详情
    
    
  },

  //##input 输入##
  input_handle(e) {
    this.setData({
      [e.currentTarget.dataset.key]: e.detail.value
    })
  },
  //##input 输入##

  _info() { // 检修详情
    var params = {
      check_id: this.data.check_id,
      station_id: this.data.station_id,
      ticket_num: this.data.ticket_num ,
    }
    api.$get(api.checkManage.info, params).then((res) => {
      this.setData({
        info: res.data,
        status: res.data.status,
        status_f: res.data.status,
        _longitude:res.data.longitude || 116.3972282409668,
        _latitude:res.data.latitude ||  39.90960456049752,
        address:res.data.address,
        markers:[//地图图标
         {
         id: 0,
         iconPath: "/assets/map_localtion_red.png",
         longitude: res.data.longitude || 116.3972282409668,
         latitude: res.data.latitude || 39.90960456049752,
         width: 30,
         height: 30,
         }
       ]
      })
      if(res.data.status=='0'){
          this.setData({
            tabList: [
              { name: '执行计划', type: 1 }, 
            ], // tab
          })
      }
      this.getSourceImage()//报修或者缺陷的图片
    })
  },

  tabHanlde(e) {
    var { index } = e.currentTarget.dataset;
    if (index == this.data.currentTab) return
    this.setData({
      currentTab: index
    })
  },
  onChange({ detail }) { 
    if (this.data.status_f==0 && detail){ // 未检修（选择的true）
      this.setData({
        status:1
      })
    } else if (this.data.status_f == 0 && !detail) {// 未检修（选择的false）
      this.setData({
        status: 0
      })
    } else if (this.data.status_f == 1 && detail) {// 已检修（选择的true）
      this.setData({
        status: 2
      })
    } else if (this.data.status_f == 1 && !detail) {// 已检修（选择的false）
      this.setData({
        status: 1
      }) 
    }
  },

  updateHandle() { // 检修保存
    var params = {
      ticket_num: this.data.ticket_num,
      status: this.data.status,
      result: this.data.result
    }
    api.$post(api.checkManage.update, params).then((res) => {
      $.toast('保存成功')
    })
  },

  toDefectManageFlawRegister(e) { // 新增缺陷
    var data=this.data.info;
    data.source='检修';
    // console.log("---------"+JSON.stringify(this.data.info))
    $.linkurl(`/pages/defectManage/defectManageFlawRegister/defectManageFlawRegister?info=${JSON.stringify(this.data.info)}&type=3`)
  },
 
  onChangeCell(event) {
    // this.setData({
    //   activeNames: event.detail
    // });
  },
  closeHandle(){
    Dialog.confirm({
      message: '确定删除吗？'
    }).then(() => {
      console.log('xxxxxxx')
    });
  },

  onChangex(event) {
    this.setData({
      activeNames: event.detail
    });
  },
  upPicsHandle(e) { // ##图片组件传出来的数据##
    var { pics, key } = e.detail
    this.setData({
      [key]: pics.length>0?pics[0]:[]
    })
    console.log(pics, key)
  },
  addHandle(e){ // 添加
    this.setData({
      list: [...this.data.list, '']
    })
    console.log(e)
  },
  delHandle(e){ // 删除
    var { index } = $.detail(e)
    var list =this.data.list
    list.splice(index,1)
    this.setData({
      list
    })
  },
  callHandle(e) {
    var { phone } = $.detail(e)
    $.call(phone)
  },
  async startPlan(){//执行检修计划
    var latitude=this.data.info.latitude ||'';
    var longitude=this.data.info.longitude ||'';
    var distance= await app.getDistance(parseFloat(latitude),parseFloat(longitude));
    // var distance=0.1;
    console.log("距离",distance)
    if(typeof(distance)=='number'){
      if(distance>5 && wx.getStorageSync('user_id')!=1){//距离较远不允许执行计划
        $.toast('您当前位置距目标位置较远,无法开始计划任务')
        return
      }
    }
      var params={
        "ticket_num":this.data.info.ticket_num,
        "status":'1',//状态变为 1：检修中
      };
      api.$post(api.checkManage.update,params).then((res)=>{
          if(res.data!=null){
            $.toast("执行成功");
            setTimeout(()=>{
              $.linkurl('', 'back')
            },1500)
          }else{
            $.toast('任务繁忙，请稍后再试')
          }
      })
  },
  openLoseHandle() { // 打开作废
    this.setData({ isLose: true })
  },
  setZuoFei(){
    if($.isNull(this.data.invalidReason)){
      $.toast("作废原因不能为空")
        return
    }
    var params={
    
      "ticket_num":this.data.info.ticket_num,
      "status":'3',//状态变为 3：已作废
      "invalidReason":this.data.invalidReason,//作废原因
      "invalidPersonid":wx.getStorageSync('user_id'),//作废人id
      "invalidPerson":wx.getStorageSync('user_name'),//作废人
    };
    api.$post(api.checkManage.update,params).then((res)=>{
        if(res.data!=null){
          $.toast("作废成功");
          setTimeout(()=>{
            $.linkurl('', 'back')
          },1500)
        }else{
          $.toast('任务繁忙，请稍后再试')
        }
    })
  },
  finishPlan(){
    if($.isNull(this.data.result)){
        $.toast("请填写检修结果");
    // }else if($.isNull(this.data.image1) || $.isNull(this.data.image2) ||$.isNull(this.data.image3)){
    //     $.toast("请上传三张检修图片");
    }else{
      var params={
        "ticket_num":this.data.info.ticket_num,
        "status":'2',//状态变为 2：已检修
        "result":this.data.result,
        "image1":this.data.image1,
        "image2":this.data.image2,
        "image3":this.data.image3,
      };
      api.$post(api.checkManage.update,params).then((res)=>{
          if(res.data!=null){
            $.toast("检修完成");
            setTimeout(()=>{
              $.linkurl('', 'back')
            },1500)
          }else{
            $.toast('任务繁忙，请稍后再试')
          }
      })
    }

  },
  getSourceImage(){
    //查询报修或者的详情
    var params1 = {
      "link_ticket": this.data.info.defectNumber,
      'defectNumber':this.data.info.defectNumber,
    }
    api.$get(api.repairsManage.infoByLinkticket, params1).then((res) => {
      this.setData({
        sourceImage: res.data
      })
    })
  },
  openMapHandle(){ // 打卡地图
    if($.isNull(this.data._latitude) || $.isNull(this.data._longitude)){
      $.toast("对不起,该厂站未提供经纬度,无法开启地图服务")
      return
    }
    wx.openLocation({
      latitude: this.data._latitude,
      longitude: this.data._longitude,
      address: this.data.address,
      scale: 18
    })
  },
})